package com.platform.server.service.impl;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.platform.server.common.Constant;
import com.platform.server.dao.IdentityAuthenticationDao;
import com.platform.server.dao.MessageDao;
import com.platform.server.dao.ServerDao;
import com.platform.server.dao.UserDao;
import com.platform.server.dao.VipDao;
import com.platform.server.response.pojo.ReturnData;
import com.platform.server.service.VipService;
import com.platform.server.util.CfbpayDemoUtils;
import com.platform.server.util.WxpayDemoUtils;
import com.szrca.ima.utils.MD5Util;
import com.szrca.ima.utils.StringTools;

@Service
@Transactional
public class VipServiceImpl implements VipService {

    @Autowired
    private VipDao vipDao;

    @Autowired
    private ServerDao serverDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private MessageDao messageDao;

    @Autowired
    private IdentityAuthenticationDao identityAuthenticationDao;

    /**
     * 查看自己的vip会员
     */
    @Override
    public ReturnData selectVipPage(String id) {
        if (StringTools.isEmpty(id)) {
            return new ReturnData(12, "参数有误");
        }
        Map<String, Object> map = vipDao.selectVipPage(id);
        if (map == null) {
            return new ReturnData(100, "您还不是vip，请先成为vip!");
        }
        return new ReturnData(map, 200, "成功");
    }

    /**
     * 成为会员
     */
    @Override
    public ReturnData insertVip(String id, String payMethod, String body, String subject, String payMoney, String ip, String password, String type) throws Exception {
        if (StringTools.isEmpty(id) || StringTools.isEmpty(payMoney) || StringTools.isEmpty(body) || StringTools.isEmpty(subject)
                || StringTools.isEmpty(payMoney) || StringTools.isEmpty(ip)|| StringTools.isEmpty(type)) {
            return new ReturnData(12, "参数有误");
        }
        ReturnData ReturnData = new ReturnData();
        String orderid = WxpayDemoUtils.getRandomString(16);
        if ("1".equals(payMethod)) {
            ReturnData = WxpayDemoUtils.wxPay(body, orderid, payMoney, ip, id + "," + payMethod + "," + payMoney + "," + orderid+ "," + type);
        } else if ("2".equals(payMethod)) {
            ReturnData = CfbpayDemoUtils.returnAlipayPayParam(body, subject, orderid, payMoney, id + "," + payMethod + "," + payMoney + "," + orderid+ "," + type);
        } else if ("3".equals(payMethod)) {
            Map<String, Object> usermap = serverDao.selectUserMoney(id);
            if (usermap == null) {
                return new ReturnData(15, "未找到该用户信息");
            }
            String pay_password = (String) usermap.get("pay_password");        //用户钱包密码
            if (StringTools.isEmpty(pay_password)) {
                return new ReturnData(20, "请先设置支付密码");
            }
            String money = usermap.get("money")
                                  .toString();        //用户钱包金额
            if (Double.parseDouble(money) < Double.parseDouble(payMoney)) {
                return new ReturnData(30, "钱包金额不足，请先充值");
            }
            if (!MD5Util.getMD5(password)
                        .equals(pay_password)) {
                return new ReturnData(40, "密码错误");
            }
            /**
             * 增加用户记录
             */
            Map<String, Object> platform_map = serverDao.selectUserMoney("1");
            String platform_money = platform_map.get("money").toString();
            serverDao.insertCancelOrder(id, payMoney, "会员", orderid,Double.parseDouble(money) - Double.parseDouble(payMoney)+"",Constant.EXPEND,Double.valueOf(platform_money)+Double.valueOf(payMoney)+"",null);
            //serverDao.insertCancelOrder("1",payMoney,"平台会员收入",orderid,Double.valueOf(platform_money)+Double.valueOf(payMoney)+"",Constant.INCOME);
            platform_money=Double.valueOf(platform_money)+Double.valueOf(payMoney)+"";
            String selectEnterUser = userDao.selectEnterUser(id);
        	String is_auth="1";
        	if(!StringTools.isEmpty(selectEnterUser)&&selectEnterUser.equals("1")){
        		is_auth="2";
        	}
       	 DecimalFormat df = new DecimalFormat("######0.00");
        	Map<String, Object> selectRate2 = serverDao.selectRate();
        	 Double royalty =0D;
        	if(type.equals("1")){
                String selectParent = userDao.selectParent(id);
                if(!StringTools.isEmpty(selectParent)){
                	String selectEntMember1 = serverDao.selectisVip1(selectParent);
                	String selectEntMember2 = serverDao.selectisVip2(selectParent);
                	Map<String, Object> map1 = serverDao.selectUserMoney(selectParent);
                	String money1 = map1.get("money")
                			.toString();
                	if(!StringTools.isEmpty(selectEntMember1)&&selectEntMember1.equals("1")){
                		royalty += Double.parseDouble( selectRate2.get("vip_recommend_one").toString());
                		serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid, Double.valueOf(money1) + royalty + "", Constant.INCOME, Double.valueOf(platform_money) -royalty+"" , null,id);
                		//加入提成
                		Map<String, Object> hashMap = new HashMap<String, Object>();
                		hashMap.put("user_id", selectParent);
                		hashMap.put("money", royalty);
                		serverDao.updateServerUserMoney(hashMap);
                	}
                	if(!StringTools.isEmpty(selectEntMember2)&&selectEntMember2.equals("1")){
                		royalty += Double.parseDouble( selectRate2.get("twovip_recommend_one").toString());
                		serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid, Double.valueOf(money1) + royalty + "", Constant.INCOME, Double.valueOf(platform_money) -royalty+"" , null,id);
                		//加入提成
                		Map<String, Object> hashMap = new HashMap<String, Object>();
                		hashMap.put("user_id", selectParent);
                		hashMap.put("money", royalty);
                		serverDao.updateServerUserMoney(hashMap);
                	}
                }
        	}
        	if(type.equals("2")){
        		is_auth="3";
        		  String selectParent = userDao.selectParent(id);
                  if(!StringTools.isEmpty(selectParent)){
                  	String selectEntMember2 = serverDao.selectisVip2(selectParent);
                  	Map<String, Object> map1 = serverDao.selectUserMoney(selectParent);
                  	String money1 = map1.get("money")
                  			.toString();
                  	if(!StringTools.isEmpty(selectEntMember2)&&selectEntMember2.equals("1")){
                  		royalty += Double.parseDouble( selectRate2.get("twovip_recommend_two").toString());
                  		serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid, Double.valueOf(money1) + royalty + "", Constant.INCOME, Double.valueOf(platform_money) -royalty+"" , null,id);
                  		//加入提成
                  		Map<String, Object> hashMap = new HashMap<String, Object>();
                  		hashMap.put("user_id", selectParent);
                  		hashMap.put("money", royalty);
                  		serverDao.updateServerUserMoney(hashMap);
                  	}
                  }
        	}
        	if(type.equals("3")){
        	    String selectParent = userDao.selectParent(id);
                if(!StringTools.isEmpty(selectParent)){
                	String selectEntMember1 = serverDao.selectisVip1(selectParent);
                	String selectEntMember2 = serverDao.selectisVip2(selectParent);
                	Map<String, Object> map1 = serverDao.selectUserMoney(selectParent);
                	String money1 = map1.get("money")
                			.toString();
                	if(!StringTools.isEmpty(selectEntMember1)&&selectEntMember1.equals("1")){
                		royalty += Double.parseDouble( selectRate2.get("vip_recommend_ent").toString());
                		serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid, Double.valueOf(money1) + royalty + "", Constant.INCOME, Double.valueOf(platform_money) -royalty+"" , null,id);
                		//加入提成
                		Map<String, Object> hashMap = new HashMap<String, Object>();
                		hashMap.put("user_id", selectParent);
                		hashMap.put("money", royalty);
                		serverDao.updateServerUserMoney(hashMap);
                	}
                	if(!StringTools.isEmpty(selectEntMember2)&&selectEntMember2.equals("1")){
                		royalty += Double.parseDouble( selectRate2.get("twovip_recommend_ent").toString());
                		serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid, Double.valueOf(money1) + royalty + "", Constant.INCOME, Double.valueOf(platform_money) -royalty+"" , null,id);
                		//加入提成
                		Map<String, Object> hashMap = new HashMap<String, Object>();
                		hashMap.put("user_id", selectParent);
                		hashMap.put("money", royalty);
                		serverDao.updateServerUserMoney(hashMap);
                	}
                }
        	}
            serverDao.returnUserMoney("1",Double.valueOf(platform_money)-Double.valueOf(royalty)+"");
            Map<String, Object> userhashMap = new HashMap<>();
            userhashMap.put("userid", id);
            userhashMap.put("money", Double.parseDouble(money) - Double.parseDouble(payMoney));
            int flag1 = serverDao.UpdateUserMoney(userhashMap);        //减少用户钱包金额
            //成为会员之前查看该用户是否有开通过会员
            Map<String, Object> map = vipDao.selectVipCount(id);
            //添加自己的消息
            Map<String, Object> hm = new HashMap<>();
            hm.put("title", "购买会员成功");
            hm.put("type", "1");
            hm.put("recevicer_id", id);
            hm.put("content", "购买会员成功");
            messageDao.insertMessage(hm);
            if (map != null) {
                //修改该用户的开通会员次数
                Integer counts = Integer.parseInt(map.get("counts")
                                                     .toString()) + 1;
                int flag = vipDao.updateVip(id, payMethod, payMoney, orderid, counts.toString(),is_auth);
                if (flag > 0) {
                    return new ReturnData(200, "成功");
                }

            } else {
                int flag = vipDao.insertVip(id, payMethod, payMoney, orderid,is_auth);
                if (flag > 0) {
                    return new ReturnData(200, "成功");
                }
            }
        }
        return ReturnData;
    }

	@Override
	public ReturnData selectAgreement() {
		// TODO Auto-generated method stub
		Map<String, Object> selectAgreement = vipDao.selectAgreement();
		if(selectAgreement!=null){
		       return new ReturnData(selectAgreement, 200, "成功");
		}else{
			  return new ReturnData(100, "没有vip协议!");
		}
	}

	@Override
	public ReturnData selectEquity() {
		// TODO Auto-generated method stub
		Map<String, Object> selectEquity = vipDao.selectEquity();
		if(selectEquity!=null){
		       return new ReturnData(selectEquity, 200, "成功");
		}else{
			  return new ReturnData(100, "没有vip协议!");
		}
	}
}
